package com.zjw.controller;


import com.zjw.annotation.domain.ResponseResult;
import com.zjw.annotation.domain.dto.AddUserDto;
import com.zjw.annotation.domain.dto.ChangeUserStatus;
import com.zjw.annotation.domain.dto.EditUserDto;
import com.zjw.enums.AppHttpCodeEnum;
import com.zjw.exception.SystemException;
import com.zjw.service.UserService;
import io.jsonwebtoken.lang.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system/user")
@PreAuthorize("@Ps.hasPermission('system:user:list')")
public class UserAdminController {

    @Autowired
    private UserService userService;

    @GetMapping("/list")
    @PreAuthorize("@Ps.hasPermission('system:user:query')")
    public ResponseResult getUserList(Long pageNum, Long pageSize,
                                      String userName, String phonenumber, String status){
        return userService.getUserList(pageNum, pageSize, userName, phonenumber,status);
    }

    @GetMapping("/{id}")
    @PreAuthorize("@Ps.hasPermission('system:user:query')")
    public ResponseResult getUserById(@PathVariable Long id){
        return userService.getUserById(id);
    }

    @PostMapping
    @PreAuthorize("@Ps.hasPermission('system:user:add')")
    public ResponseResult addUser(@RequestBody AddUserDto addUserDto){
        return userService.addUser(addUserDto);
    }


    @PutMapping
    @PreAuthorize("@Ps.hasPermission('system:user:edit')")
    public ResponseResult editUser(@RequestBody EditUserDto editUserDto){
        return userService.editUser(editUserDto);
    }

    @DeleteMapping("/{ids}")
    @PreAuthorize("@Ps.hasPermission('system:user:remove')")
    public ResponseResult removeUser(@PathVariable String ids){
        if(!Strings.hasText(ids))
            throw new SystemException(AppHttpCodeEnum.DATA_UNCOMPLETED);

        List<Long> idList = Arrays.stream(ids.split(",")).map(n -> Long.parseLong(n))
                .collect(Collectors.toList());
        return userService.removeUser(idList);
    }

    @PutMapping("/changeStatus")
    @PreAuthorize("@Ps.hasPermission('system:user:edit')")
    public ResponseResult changeUserStatus(@RequestBody ChangeUserStatus changeUserStatus){
        return userService.changeStatus(changeUserStatus.getUserId(), changeUserStatus.getStatus());
    }
}
